/*
 * @Author: ZhangXiaodong
 * @Date: 2025-04-11 20:56:51
 * @LastEditors: ZhangXiaodong
 * @LastEditTime: 2025-04-25 23:58:42
 * @Description: 服务端入口文件
 * @FilePath: /blog-ost/app.js
 */
const ip = require("ip");
const querystring = require("querystring");
const routers = require("./src/routers");
const { routerBlog, routerUser } = routers;

/**
 * 从 HTTP 请求中提取 POST 请求的 JSON 数据
 * @param {Object} req - HTTP 请求对象
 * @returns {Promise<Object>} - 一个 Promise，解析为包含 POST 数据的对象
 */

const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== "POST") {
      resolve({});
      return;
    }
    if (req.headers["content-type"] !== "application/json") {
      resolve({});
      return;
    }

    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      try {
        if (postData.length === 0) {
          resolve({});
          return;
        }
        const parsedData = JSON.parse(postData);
        resolve(parsedData);
      } catch (error) {
        reject(new Error("解析 POST 数据为 JSON 时出错: " + error.message));
      }
    });
  });
  return promise;
};

/**
 * 处理 HTTP 请求的主函数
 * @param {Object} req - HTTP 请求对象
 * @param {Object} res - HTTP 响应对象
 */
const app = (req, res) => {
  res.setHeader("Content-Type", "application/json");
  res.setHeader("Access-Control-Allow-Origin", "*");
  const { url } = req;
  // 拆分 URL 只执行一次，避免重复操作
  const [path, queryStr] = url.split("?");
  req.path = path;
  req.ip = ip.address();
  // 解析查询字符串
  req.query = querystring.parse(queryStr);
  req.id = req.query.id;

  getPostData(req)
    .then((body) => {
      req.body = body;
      req.author = "张晓东";
      req.userId = 1;

      // 统一处理路由函数
      const handleResult = (result) => {
        if (result) {
          result.then((data) => {
            res.end(JSON.stringify(data));
          });
          return true;
        }
        return false;
      };

      // 处理博客路由
      if (handleResult(routerBlog(req))) {
        return;
      }

      // 处理博客路由
      if (handleResult(routerUser(req))) {
        return;
      }

      // 404
      res.writeHead(404, { "Content-Type": "text/plain" });
      res.end("404 Not Found");
    })

    //统一错误处理
    .catch((error) => {
      console.error("请求处理出错:", error);
      res.writeHead(500, { "Content-Type": "text/plain" });
      res.end("500 Internal Server Error");
    });
};

module.exports = app;
